<template>
  <a-popover trigger="click" placement="leftBottom" @visibleChange="visibleChange">
    <template slot="title"> <span>自定义列</span><a-button @click="reset" style="float:right;" shape="round" size="small" type="primary">重置</a-button> </template>
    <template slot="content">
      <a-checkbox-group
        @change="onColSettingsChange"
        v-model="settingColumns"
        :defaultValue="settingColumns"
        style="width: 200px"
      >
        <a-row ref="customList">
          <template v-for="(item, index) in defColumns_">
            <template v-if="!ignoreColumns.includes(item.key) && !ignoreColumns.includes(item.dataIndex)">
              <a-col :key="item.dataIndex" :span="24"
                ><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col
              >
            </template>
          </template>
        </a-row>
      </a-checkbox-group>
    </template>
    <a-tooltip placement="top" title="自定义列">
      <a><a-icon type="setting" />设置</a>
    </a-tooltip>
  </a-popover>
</template>

<script>
import Vue from 'vue'
import Sortable from 'sortablejs'

export default {
  name: 'ListColumnsSetter',

  props: {
    columns: {
      type: Array,
      required: true,
    },
    defColumns: {
      type: Array,
      required: true,
    },
    ignoreColumns: {
      type: Array,
      default: () => ['rowIndex', 'action', 'flag'],
    },
    listName: {
      type: String,
      default: '',
    },
  },

  model: {
    prop: 'columns',
    event: 'change',
  },

  data() {
    return {
      defColumns_: [],
      settingColumns: [],
    }
  },

  computed: {
    ls_key() {
      return this.$route.name + '/' + this.listName + ':colsettings'
    },
    ls_sort_key(){
      return this.$route.name + '/' + this.listName + 'sort:colsettings'
    }
  },

  mounted() {
    let that = this
    this.defColumnsCopy = JSON.parse(JSON.stringify(this.defColumns))
    this.defSorts = []
    this.defColumnsCopy.forEach((v,k)=>{
      let key = v.dataIndex ? v.dataIndex : v.key
      that.defSorts.push(key)
    })
    this.defColumns_.push(...this.defColumns)
    this.initColumns()
  },

  methods: {
    reset(){
      Vue.ls.set(this.ls_sort_key,this.defSorts,null)
      Vue.ls.remove(this.ls_key)
      this.initColumns()
    },
    visibleChange(visible) {
      var self = this
      this.$nextTick(() => {
        // self.initSort()
      })
    },
    initSort() {
      this.sortable = Sortable.create(this.$refs.customList.$el, {
        handle: '.ant-col',
        onEnd: ({ item, newIndex, oldIndex }) => {
          // console.log(item, newIndex, oldIndex)
          // console.log(this.defColumns_);
          for (let i = 0; i < 2; i++) {
            if (this.ignoreColumns.includes(this.defColumns_[i].key) || this.ignoreColumns.includes(this.defColumns_[i].dataIndex)) {
              newIndex += 1
              oldIndex += 1
            }
          }

          let tempList = [];
          tempList.push(...this.defColumns_);

          if(newIndex<oldIndex){
            var oldItem = tempList.splice(oldIndex,1);
            tempList.splice(newIndex,0,oldItem[0]);
          }
          if(newIndex>oldIndex){
            var oldItem = tempList.splice(oldIndex,1);
            tempList.splice(newIndex,0,oldItem[0]);
          }

          this.defColumns_ = tempList;
          const columns = this.defColumns_.filter((item) => {
            if (this.ignoreColumns.includes(item.key) || this.ignoreColumns.includes(item.dataIndex)) {
              return true
            }
            if (this.settingColumns.includes(item.dataIndex)) {
              return true
            }
            return false
          })
          let sortValues = []
          columns.forEach((v,k)=>{
            if(v.key == "rowIndex"){
              return;
            }
            if (v.key == "action") {
              return;
            }
            let key = v.dataIndex ? v.dataIndex : v.key
            sortValues.push(key)
          })
          Vue.ls.set(this.ls_sort_key, sortValues,null )  //365 * 7 * 24 * 60 * 60 * 1000
          this.$emit('change', columns)
        },
      })
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns_ = colAuthFilter(this.defColumns_,'testdemo:');
      let colSettings = Vue.ls.get(this.ls_key)
      let colSorts = Vue.ls.get(this.ls_sort_key)

      if(colSorts && colSorts.length > 0){
        if(colSorts.indexOf("rowIndex") == -1){
          colSorts.unshift("rowIndex")
        }
        if(colSorts.indexOf("action") == -1){
          colSorts.unshift("action")
        }
        this.defColumns_.sort(function(a,b){
          let akey = a.dataIndex ? a.dataIndex : a.key
          let bkey = b.dataIndex ? b.dataIndex : b.key
          let ai = colSorts.indexOf(akey) == -1 ? 999 : colSorts.indexOf(akey)
          let bi = colSorts.indexOf(bkey) == -1 ? 999 : colSorts.indexOf(bkey)
          return  ai - bi
        })
      }

      let columns = []
      if (colSettings === null || colSettings === undefined) {
        let allSettingColumns = []
        this.defColumns_.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex)
        })
        this.settingColumns = allSettingColumns
        columns = this.defColumns_
      } else {
        this.settingColumns = colSettings

        columns = this.defColumns_.filter((item) => {
          if (this.ignoreColumns.includes(item.key) || this.ignoreColumns.includes(item.dataIndex)) {
            return true
          }
          if (colSettings.includes(item.dataIndex)) {
            return true
          }
          return false
        })
      }
      this.$emit('change', columns)
    },

    //列设置更改事件
    onColSettingsChange(checkedValues) {
      Vue.ls.set(this.ls_key, checkedValues,null )  //365 * 7 * 24 * 60 * 60 * 1000
      this.settingColumns = checkedValues
      let checkedColumns = []
      let noCheckedColumns = []

      for (let item of this.defColumns_) {
        if (this.ignoreColumns.includes(item.key) || this.ignoreColumns.includes(item.dataIndex)) {
          checkedColumns.push(item);
          continue;
        }
        if (!this.settingColumns.includes(item.dataIndex)) {
          noCheckedColumns.push(item);
        } else {
          checkedColumns.push(item);
        }
      }

      this.defColumns_ = checkedColumns.concat(noCheckedColumns)
      const columns = this.defColumns_.filter((item) => {
        if (this.ignoreColumns.includes(item.key) || this.ignoreColumns.includes(item.dataIndex)) {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })

      this.$emit('change', columns)
    },
  },
}
</script>
